﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace EarringsBackEnd
{
    public partial class frmEarringsTemp : Form
    {
        private bool _isMouseDown = false;
        private Point _mouseDownLocation = Point.Empty;
        int _xDifference, _yDifference;

        public frmEarringsTemp()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            //openFD.InitialDirectory = @"N:\My Documents\My Pictures";
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxOriginal.Image = Image.FromFile(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void btnRemoveBgd_Click(object sender, EventArgs e)
        {
            Bitmap myBitmap = new Bitmap(picBxOriginal.Image);

            // Get the color of a background pixel.
            Color backColor = myBitmap.GetPixel(1, 1);

            // Make backColor transparent for myBitmap.
            myBitmap.MakeTransparent(backColor);

            picBxPNG.Image = myBitmap;

            
            //int width = picBxOriginal.Width;
            //int height = picBxOriginal.Height;

            //Bitmap myBitmapPNG = new Bitmap(picBxPNG.Image);
            //System.Drawing.Image img = (System.Drawing.Image)myBitmapPNG;
            //picBxPNG.Image = img;

            //for (int x = 0; x < myBitmapPNG.Width; x++)
            //{
            //    for (int y = 0; y < myBitmapPNG.Height; y++)
            //    {
            //        Color c = myBitmapPNG.GetPixel(x, y);
            //        if ((c.B + c.R + c.G > 660))
            //        {
            //            c = Color.FromArgb(0, c.R, c.G, c.B);
            //            myBitmapPNG.SetPixel(x, y, c);
            //            myBitmapPNG.MakeTransparent(c);
            //        }

            //        //if (c.GetBrightness() > 240)
            //        //    c = Color.FromArgb(0, c.R, c.G, c.B);
                    
            //    }
            //}

            //picBxPNG.Image = myBitmapPNG;
            
        }

        public bool IsBackgroundWhite(Bitmap theImageBitmap)
        {
            Bitmap bmp = new Bitmap(theImageBitmap);
            int weight = 0;

            for (int x = 0; x < bmp.Width; x++)
            {
                weight += GetWeight(bmp.GetPixel(x, 0));
                weight += GetWeight(bmp.GetPixel(x, bmp.Height - 1));
            }

            for (int y = 0; y < bmp.Height; y++)
            {
                weight += GetWeight(bmp.GetPixel(0, y));
                weight += GetWeight(bmp.GetPixel(bmp.Width - 1, y));
            }

            if (weight > 255)
                return true;
            return false;
        }

        private int GetWeight(Color c)
        {
            if (c.R >= 200 && c.B >= 200 && c.G >= 200)
            {
                int n1 = 255 - c.R;
                int n2 = 255 - c.G;
                int n3 = 255 - c.B;
                return (int)((n1 + n2 + n3) / 3);
            }
            else
            {
                return 0;
            }
        }

        private void btnDetechColor_Click(object sender, EventArgs e)
        {
            try
            {
                Boolean IsColorFound = false;
                if (picBxOriginal.Image != null)
                {
                    //Converting loaded image into bitmap
                    Bitmap bmp = new Bitmap(picBxOriginal.Image);

                    //Iterate whole bitmap to findout the picked color
                    for (int i = 0; i < picBxOriginal.Image.Height; i++)
                    {
                        for (int j = 0; j < picBxOriginal.Image.Width; j++)
                        {
                            //Get the color at each pixel
                            Color now_color = bmp.GetPixel(j, i);

                            //Compare Pixel's Color ARGB property with the picked color's ARGB property 
                            if (now_color.ToArgb() == colorDialog1.Color.ToArgb())
                            {
                                IsColorFound = true;
                                MessageBox.Show("Color Found!");
                                break;
                            }
                        }
                        if (IsColorFound == true)
                        {
                            break;
                        }
                    }
                    if (IsColorFound == false)
                    {
                        MessageBox.Show("Selected Color Not Found.");
                    }
                }
                else
                {
                    MessageBox.Show("Image is not loaded");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void btnSavePNG_Click(object sender, EventArgs e)
        {
           
            // Displays a SaveFileDialog so the user can save the Image
            saveFD.Filter = "Portable Network Graphics|*.png";
            saveFD.Title = "Save an Image File";
            if (saveFD.ShowDialog() == DialogResult.OK)
            {
                Bitmap myBitmap = new Bitmap(picBxPNG.Image);
                System.Drawing.Image img = (System.Drawing.Image)myBitmap;
                img.Save(saveFD.FileName , ImageFormat.Png);

                MessageBox.Show("Save Complete");
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void picBxPNG_MouseDown(object sender, MouseEventArgs e)
        {
            _isMouseDown = true;
            _mouseDownLocation = new Point(e.X, e.Y);
            Point point = new Point(e.X, e.Y);
            Point point2 = e.Location;

            txtCenter.Text = "X: " + point2.X.ToString() + " - Y: " + point2.Y.ToString();
            //txtCenter.Text = "X: " + e.X.ToString() + " - Y: " + e.Y.ToString();
        }

        private void picBxPNG_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                _xDifference = _mouseDownLocation.X > e.X ? _mouseDownLocation.X - e.X : e.X - _mouseDownLocation.X;
                _yDifference = _mouseDownLocation.Y > e.Y ? _mouseDownLocation.Y - e.Y : e.Y - _mouseDownLocation.Y;
                picBxPNG.Invalidate();
            }
            
        }

        private void picBxPNG_Paint(object sender, PaintEventArgs e)
        {
            txtCenter.Text = _xDifference.ToString() + " - " + _yDifference.ToString();
            e.Graphics.DrawEllipse(Pens.Red, _mouseDownLocation.X - _xDifference, _mouseDownLocation.Y - _yDifference, _xDifference * 2, _yDifference * 2);
        }

        private void picBxPNG_MouseUp(object sender, MouseEventArgs e)
        {
            _isMouseDown = false;
        }

        //private System.Drawing.Color CalculateAverageColor(Bitmap bm)
        //{
        //    int width = bm.Width;
        //    int height = bm.Height;
        //    int red = 0;
        //    int green = 0;
        //    int blue = 0;
        //    int minDiversion = 15; // drop pixels that do not differ by at least minDiversion between color values (white, gray or black)
        //    int dropped = 0; // keep track of dropped pixels
        //    long[] totals = new long[] { 0, 0, 0 };
        //    int bppModifier = bm.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb ? 3 : 4; // cutting corners, will fail on anything else but 32 and 24 bit images

        //    BitmapData srcData = bm.LockBits(new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
        //    int stride = srcData.Stride;
        //    IntPtr Scan0 = srcData.Scan0;

        //    //unsafe
        //    //{
        //    //    byte* p = (byte*)(void*)Scan0;

        //    //    for (int y = 0; y < height; y++)
        //    //    {
        //    //        for (int x = 0; x < width; x++)
        //    //        {
        //    //            int idx = (y * stride) + x * bppModifier;
        //    //            red = p[idx + 2];
        //    //            green = p[idx + 1];
        //    //            blue = p[idx];
        //    //            if (Math.Abs(red - green) > minDiversion || Math.Abs(red - blue) > minDiversion || Math.Abs(green - blue) > minDiversion)
        //    //            {
        //    //                totals[2] += red;
        //    //                totals[1] += green;
        //    //                totals[0] += blue;
        //    //            }
        //    //            else
        //    //            {
        //    //                dropped++;
        //    //            }
        //    //        }
        //    //    }
        //    //}

        //    int count = width * height - dropped;
        //    int avgR = (int)(totals[2] / count);
        //    int avgG = (int)(totals[1] / count);
        //    int avgB = (int)(totals[0] / count);

        //    return System.Drawing.Color.FromArgb(avgR, avgG, avgB);
        //}
    }
}
